# -*- coding: utf-8 -*-
"""
文件传输进度显示窗口模块
实现文件上传下载进度的实时显示功能
"""

import time
from PySide2.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QProgressBar,
    QPushButton, QFrame
)
from PySide2.QtCore import Qt, QTimer, Signal
from PySide2.QtGui import QFont
from gglobal import logger
from .custom_progress import CustomProgressBar, ProgressStyle, ThemeMode
from ..handlercore.signal_manager import ComponentSignalManager


class ProgressInfoWidget(QDialog):
    """文件传输进度显示窗口"""
    
    # 信号定义
    cancel_requested = Signal()  # 取消传输请求信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("progress_info_widget")
        
        # 传输状态变量
        self.start_time = None
        self.current_filename = ""
        self.total_bytes = 0
        self.transferred_bytes = 0
        self.current_speed = 0.0
        
        # 信号连接检查计数器（每10秒检查一次）
        self.signal_check_counter = 0
        
        # 定时器用于更新已用时间
        self.timer = QTimer(self)
        
        # 初始化信号管理器
        self.signal_manager = ComponentSignalManager("ProgressInfoWidget", self)
        
        self.init_ui()
        self.setup_signal_connections()
        
        logger.info("传输进度窗口初始化完成")
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("文件传输进度")
        self.setModal(True)
        self.setFixedSize(400, 350)
        self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint | Qt.CustomizeWindowHint)
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)
        
        # 创建标题区域
        self.create_title_area(main_layout)
        
        # 创建分隔线
        separator = QFrame()
        separator.setObjectName("progress_separator")
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        main_layout.addWidget(separator)
        
        # 创建文件信息区域
        self.create_file_info_area(main_layout)
        
        # 创建进度条区域
        self.create_progress_area(main_layout)
        
        # 创建传输信息区域
        self.create_transfer_info_area(main_layout)
        
        # 创建按钮区域
        self.create_button_area(main_layout)
        
    def create_title_area(self, parent_layout):
        """创建标题区域"""
        self.title_label = QLabel("SFTP传输...")
        self.title_label.setObjectName("progress_title_label")
        self.title_label.setAlignment(Qt.AlignCenter)
        self.title_label.setFixedHeight(30)
        parent_layout.addWidget(self.title_label,stretch=2)
        
    def create_file_info_area(self, parent_layout):
        """创建文件信息区域"""
        file_layout = QVBoxLayout()
        file_layout.setSpacing(8)
        
        # 文件名标签
        filename_layout = QHBoxLayout()
        filename_layout.setSpacing(3)
        
        filename_title = QLabel("文件名:")
        filename_title.setObjectName("progress_label_title")
        filename_layout.addWidget(filename_title)
        
        self.filename_label = QLabel("未知文件")
        self.filename_label.setObjectName("progress_filename_label")
        filename_layout.addWidget(self.filename_label)
        filename_layout.addStretch()
        
        file_layout.addLayout(filename_layout)
        parent_layout.addLayout(file_layout,stretch=1)
        
    def create_progress_area(self, parent_layout):
        """创建进度条区域"""
        progress_layout = QVBoxLayout()
        progress_layout.setSpacing(6)
        
        # 使用自定义TRANSFER样式进度条
        self.progress_bar = CustomProgressBar(ProgressStyle.TRANSFER, ThemeMode.LIGHT)
        self.progress_bar.setObjectName("progress_transfer_bar")
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(100)
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(True)
        progress_layout.addWidget(self.progress_bar)  
        parent_layout.addLayout(progress_layout,stretch=3)
        
    def create_transfer_info_area(self, parent_layout):
        """创建传输信息区域"""
        info_layout = QVBoxLayout()
        info_layout.setSpacing(8)
        
        # 传输速度
        speed_layout = QHBoxLayout()
        speed_title = QLabel("传输速度:")
        speed_title.setObjectName("progress_label_title")
        speed_layout.addWidget(speed_title)
        
        self.speed_label = QLabel("0 B/s")
        self.speed_label.setObjectName("progress_speed_label")
        speed_layout.addWidget(self.speed_label)
        speed_layout.addStretch()
        
        info_layout.addLayout(speed_layout)
        
        # 已传输大小
        size_layout = QHBoxLayout()
        size_title = QLabel("已传输:")
        size_title.setObjectName("progress_label_title")
        size_layout.addWidget(size_title)
        
        self.size_label = QLabel("0 B / 0 B")
        self.size_label.setObjectName("progress_size_label")
        size_layout.addWidget(self.size_label)
        size_layout.addStretch()
        
        info_layout.addLayout(size_layout)
        
        # 已用时间
        time_layout = QHBoxLayout()
        time_title = QLabel("已用时间:")
        time_title.setObjectName("progress_label_title")
        time_layout.addWidget(time_title)
        
        self.time_label = QLabel("00:00:00")
        self.time_label.setObjectName("progress_time_label")
        time_layout.addWidget(self.time_label)
        time_layout.addStretch()
        
        info_layout.addLayout(time_layout)
        
        parent_layout.addLayout(info_layout,stretch=3)
        
    def create_button_area(self, parent_layout):
        """创建按钮区域"""
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        # 取消按钮
        self.cancel_button = QPushButton("取消")
        self.cancel_button.setObjectName("progress_cancel_button")
        self.cancel_button.setMinimumSize(80, 32)
        button_layout.addWidget(self.cancel_button,stretch=1)
        
        parent_layout.addLayout(button_layout,stretch=3)
        
    def setup_signal_connections(self):
        """设置信号连接"""
        # 注册取消按钮信号连接
        self.signal_manager.register_connection(
            "cancel_button_clicked",
            self.cancel_button.clicked,
            self.on_cancel_clicked,
            group="ui_signals"
        )
        
        # 注册定时器信号连接
        self.signal_manager.register_connection(
            "timer_timeout",
            self.timer.timeout,
            self.update_elapsed_time,
            group="timer_signals"
        )
        
        # 连接所有信号
        self.signal_manager.connect_all()
        
    def reconnect_signals(self):
        """重新连接所有信号（用于Nuitka打包环境的稳定性）"""
        # 断开所有现有连接
        self.signal_manager.disconnect_all()
        
        # 重新连接所有信号
        self.signal_manager.connect_all()
        
        logger.debug("信号重新连接完成")
        
    def check_signal_connections(self):
        """检查信号连接状态并在需要时重新连接"""
        connections_ok = True
        
        # 检查取消按钮信号连接
        if not self.signal_manager.get_connection_status("cancel_button_clicked"):
            logger.warning("取消按钮信号连接已断开，尝试重新连接")
            connections_ok = False
            
        # 检查定时器信号连接
        if not self.signal_manager.get_connection_status("timer_timeout"):
            logger.warning("定时器信号连接已断开，尝试重新连接")
            connections_ok = False
            
        # 如果有连接断开，重新连接所有信号
        if not connections_ok:
            self.reconnect_signals()
            logger.info("信号连接状态检查完成，已重新连接断开的信号")
        else:
            logger.debug("所有信号连接正常")
            
        return connections_ok
        
    def reset_for_reuse(self):
        """重置窗口状态以便重复使用"""
        # 停止定时器
        if self.timer.isActive():
            self.timer.stop()
            
        # 重置状态变量
        self.start_time = None
        self.current_filename = ""
        self.total_bytes = 0
        self.transferred_bytes = 0
        self.current_speed = 0.0
        self.signal_check_counter = 0  # 重置信号检查计数器
        
        # 重置UI
        self.title_label.setText("SFTP传输...")
        self.filename_label.setText("未知文件")
        self.progress_bar.setValue(0)
        self.speed_label.setText("0 B/s")
        self.size_label.setText("0 B / 0 B")
        self.time_label.setText("00:00:00")
        self.cancel_button.setText("取消")
        
        # 检查并重新连接信号
        self.check_signal_connections()
        
        logger.debug("进度窗口已重置为初始状态")
        
    def set_theme_mode(self, theme_mode: ThemeMode):
        """设置进度条主题模式
        
        Args:
            theme_mode: 主题模式（LIGHT 或 DARK）
        """
        if hasattr(self, 'progress_bar') and isinstance(self.progress_bar, CustomProgressBar):
            self.progress_bar.set_theme(theme_mode)
            logger.info(f"进度条主题已切换为: {theme_mode.value}")
        
    def start_transfer(self, filename, operation_type="下载"):
        """开始传输
        
        Args:
            filename: 文件名
            operation_type: 操作类型（"上传" 或 "下载"）
        """
        self.current_filename = filename
        self.start_time = time.time()
        self.transferred_bytes = 0
        self.total_bytes = 0
        self.current_speed = 0.0
        
        # 检查并重新连接信号以确保在Nuitka打包环境中的稳定性
        self.check_signal_connections()
        
        # 更新UI
        self.title_label.setText(f"正在{operation_type}文件...")
        self.filename_label.setText(filename)
        self.progress_bar.setValue(0)
        self.speed_label.setText("0 B/s")
        self.size_label.setText("0 B / 0 B")
        self.time_label.setText("00:00:00")
        
        # 重置按钮文本
        self.cancel_button.setText("取消")
        
        # 启动定时器
        self.timer.start(1000)  # 每秒更新一次
        
        logger.info(f"开始{operation_type}文件: {filename}")
        
    def update_progress(self, filename, transferred, total, speed):
        """更新传输进度
        
        Args:
            filename: 文件名
            transferred: 已传输字节数
            total: 总字节数
            speed: 传输速度（字节/秒）
        """
        self.current_filename = filename
        self.transferred_bytes = transferred
        self.total_bytes = total
        self.current_speed = speed
        
        # 计算进度百分比
        if total > 0:
            percentage = int((transferred / total) * 100)
        else:
            percentage = 0
            
        # 更新进度条
        self.progress_bar.setValue(percentage)
        
        # 更新传输速度
        self.speed_label.setText(self.format_speed(speed))
        
        # 更新传输大小
        self.size_label.setText(f"{self.format_size(transferred)} / {self.format_size(total)}")
        
        # logger.debug(f"更新进度: {filename} - {percentage}% - {self.format_speed(speed)}")
        
    def update_elapsed_time(self):
        """更新已用时间"""
        if self.start_time:
            elapsed = time.time() - self.start_time
            hours = int(elapsed // 3600)
            minutes = int((elapsed % 3600) // 60)
            seconds = int(elapsed % 60)
            time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
            self.time_label.setText(time_str)
            
        # 定期检查信号连接状态（每10秒检查一次）
        self.signal_check_counter += 1
        if self.signal_check_counter >= 10:  # 10秒检查一次
            self.signal_check_counter = 0
            self.check_signal_connections()
            
    def finish_transfer(self, success=True, message=""):
        """完成传输
        
        Args:
            success: 是否成功
            message: 完成消息
        """
        self.timer.stop()
        
        if success:
            self.title_label.setText("传输完成")
            self.progress_bar.setValue(100)
            self.cancel_button.setText("关闭")
        else:
            self.title_label.setText(f"传输失败: {message}")
            self.cancel_button.setText("关闭")
            
        # 检查并重新连接取消按钮信号，确保"关闭"功能正常工作
        self.check_signal_connections()
            
        logger.info(f"传输完成: success={success}, message={message}")
        
    def on_cancel_clicked(self):
        """取消按钮点击处理"""
        # 在处理点击事件前检查信号连接状态
        self.check_signal_connections()
        
        if self.cancel_button.text() == "取消":
            self.cancel_requested.emit()
            logger.info("用户请求取消传输")
        else:
            self.accept()  # 关闭对话框
            
    def format_size(self, size_bytes):
        """格式化文件大小
        
        Args:
            size_bytes: 字节数
            
        Returns:
            格式化的大小字符串
        """
        if size_bytes == 0:
            return "0 B"
        
        size_names = ["B", "KB", "MB", "GB", "TB"]
        i = 0
        while size_bytes >= 1024.0 and i < len(size_names) - 1:
            size_bytes /= 1024.0
            i += 1
        return f"{size_bytes:.1f} {size_names[i]}"
        
    def format_speed(self, speed_bytes_per_sec):
        """格式化传输速度
        
        Args:
            speed_bytes_per_sec: 每秒字节数
            
        Returns:
            格式化的速度字符串
        """
        return f"{self.format_size(speed_bytes_per_sec)}/s"
        
    def closeEvent(self, event):
        """窗口关闭事件"""
        self.timer.stop()
        # 清理信号连接
        if hasattr(self, 'signal_manager'):
            self.signal_manager.disconnect_all()
        super().closeEvent(event)
        
    def __del__(self):
        """析构函数，确保资源清理"""
        try:
            if hasattr(self, 'timer') and self.timer:
                self.timer.stop()
            if hasattr(self, 'signal_manager'):
                self.signal_manager.disconnect_all()
        except Exception as e:
            logger.debug(f"ProgressInfoWidget析构时清理资源异常: {e}")